package com.yun.config;

import com.yun.unit.JwtTokenUtil;
import com.yun.unit.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class MyLoginTestFilter extends OncePerRequestFilter {
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    /**
     * httpServletRequest 前端发来的请求
     * httpServletResponse 响应
     * filterChain 过滤器
     * @param httpServletRequest
     * @param httpServletResponse
     * @param filterChain
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        //获取请求头中的token
        String authorization = httpServletRequest.getHeader("Authorization");
        System.out.println("authorization:"+authorization);
        if (authorization != null){
            //只要不是登录请求，authorization都不是空的
            String userName = jwtTokenUtil.getUserNameFromToken(authorization);
            if (userName!=null){
                System.out.println("说明校验成功");
                //去redis中取出userName的值
                //需要进行强转，在存redis中时，使用的是LoginUser对象
                LoginUser o = (LoginUser) redisTemplate.opsForValue().get(userName);
                //获取出角色和权限
                List<String> jueseheguize = o.getJueseheguize();
                //通过Stream 将角色和权限存放到一个新的集合中
                List<SimpleGrantedAuthority> collect = jueseheguize.stream().map(item -> new SimpleGrantedAuthority(item)).collect(Collectors.toList());
                //最后将用户名，密码，角色和权限赋值到SecuityContextHolder中
                UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(userName,o.getPassword(),collect);
                SecurityContext context = SecurityContextHolder.getContext();
                context.setAuthentication(usernamePasswordAuthenticationToken);
            }else{
                System.out.println("说明校验失败");
            }
        }else {
            System.out.println("登录请求");
        }
        filterChain.doFilter(httpServletRequest,httpServletResponse);
    }
}
